import dayjs from "dayjs";
import Form from "../form.vue";
import { handleTree } from "@/utils/tree";
import { deptApi } from "@/api/organization/department";
import { usePublicHooks, formatHigherDeptOptions } from "@/utils/viewsPublic";
import { reactive, ref, onMounted, Ref, shallowRef } from "vue";
import { cloneDeep, isFunction } from "@pureadmin/utils";
import { staffApi } from "@/api/organization/staff";
import { hasAuth } from "@/router/utils";

export function useDept(tableRef: Ref) {
  const { tagStyle } = usePublicHooks();
  const staffList = ref();
  const api = reactive({
    list: deptApi.list,
    fields: deptApi.fields,
    save: deptApi.save,
    delete: deptApi.delete
  });
  const auth = reactive({
    list: true,
    create: hasAuth("add"),
    update: hasAuth("edit"),
    delete: hasAuth("delete"),
    batchDelete: hasAuth("delete"),
    import: hasAuth("import"),
    export: hasAuth("export"),
    download: hasAuth("download"),
    auth: hasAuth("auth")
  });
  const columns: TableColumnList = [
    {
      label: "部门名称",
      prop: "name",
      width: 180,
      align: "left"
    },
    {
      label: "排序",
      prop: "sort",
      minWidth: 70
    },
    {
      label: "状态",
      prop: "status",
      minWidth: 100,
      cellRenderer: ({ row, props }) => (
        <el-tag size={props.size} style={tagStyle.value(row.status)}>
          {row.status === 1 ? "启用" : "停用"}
        </el-tag>
      )
    },
    {
      label: "创建时间",
      minWidth: 200,
      prop: "create_time",
      formatter: ({ create_time }) =>
        create_time ? dayjs(create_time).format("YYYY-MM-DD HH:mm:ss") : ""
    },
    {
      label: "备注",
      prop: "remark",
      minWidth: 320
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];
  const editForm = shallowRef({
    form: Form,
    props: {
      formInline: row => {
        return {
          higherDeptOptions: formatHigherDeptOptions(
            cloneDeep(tableRef.value.dataList)
          ),
          pid: row?.pid ?? 0,
          name: row?.name ?? "",
          staff_id: row?.staff_id != 0 ? row?.staff_id : null,
          phone: row?.phone ?? "",
          email: row?.email ?? "",
          sort: row?.sort ?? 0,
          status: row?.status ?? 1,
          remark: row?.remark ?? "",
          staffList: staffList.value,
          id: row?.id ?? 0
        };
      }
    }
  });
  function resultFormat(data) {
    return handleTree(data, "id", "pid");
  }
  function openDialog(row) {
    if (tableRef.value && isFunction(tableRef.value.openDialog)) {
      tableRef.value.openDialog(true, { pid: row.id });
    } else {
      console.error("openDialog method is not defined on the child component");
    }
  }

  onMounted(() => {
    staffApi.list({ page_type: 0 }).then(res => {
      if (res.code == 200) [(staffList.value = res.data.list)];
    });
  });
  return { api, auth, resultFormat, columns, editForm, openDialog };
}
